package mysql

import (
	"fmt"
	"lwa-go/config"

	_ "github.com/go-sql-driver/mysql"

	"github.com/jmoiron/sqlx"
)

type Novel struct {
	Id        int    `db:"id"`
	NovelName string `db:"novel_name"`
}

type Chapter struct {
	Id          int    `db:"id"`
	ChapterName string `db:"chapter_name"`
	Content     string `db:"content"`
	IsVip       string `db:"is_vip"`
	NovelId     int    `db:"novel_id"`
	OrderNum    int    `db:"order_num"`
}

var DB *sqlx.DB

func init() {
	dbConfig := config.Conf.Database
	dbSoureName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Database)
	database, err := sqlx.Open("mysql", dbSoureName)
	if err != nil {
		panic(err)
	}
	DB = database
}

func SelectNovelFromId(novelId int) []Novel {
	var novels []Novel
	err := DB.Select(&novels, "select id, novel_name from novels where id = ?", novelId)
	if err != nil {
		panic(err)
	}
	return novels
}

func SelectChapterFromNovel(novelId int) []Chapter {
	var chapters []Chapter
	err := DB.Select(&chapters, "select id, chapter_name, content, is_vip from chapters where novel_id = ? ", novelId)
	if err != nil {
		panic(err)
	}
	return chapters
}

func SelectChapterFromId(chapterId int) Chapter {
	var chapters []Chapter
	err := DB.Select(&chapters, "select id, chapter_name, content, is_vip from chapters where id = ? ", chapterId)
	if err != nil {
		panic(err)
	}
	return chapters[0]
}

func UpdateChapterContent(chapterId int, content string) int {
	res, err := DB.Exec("update chapters set content =  ? where id = ?", content, chapterId)
	if err != nil {
		panic(err)
	}
	row, err := res.RowsAffected()
	if err != nil {
		panic(err)
	}
	return int(row)
}

func SelectChapersOrderNum(novelId int) []Chapter {
	var chapters []Chapter
	err := DB.Select(&chapters, "select id, order_num from chapters order by id asc")
	if err != nil {
		panic(err)
	}
	return chapters
}

func SetChapterOrderNum(novelId, chapterId, orderNum int) int {
	res, err := DB.Exec("update chapters set order_num = ? where novel_id = ? and id = ?", orderNum, novelId, chapterId)
	if err != nil {
		panic(err)
	}
	row, err := res.RowsAffected()
	if err != nil {
		panic(err)
	}
	return int(row)
}
